package com.ambimmort.shj.service.policysyn;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.db.bean.*;
import com.ambimmort.umessage.uc.incoming.xC2;
import com.ambimmort.umessage.util.HexUtil;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2015/7/31.
 */
@Service
public class PolicysynService {
//    @Autowired
//    private SessionFactory hibernateSessionFactory;

    ResultSet rs = null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * @param dpiId
     * @return
     */

    public String getReportedVersionDomain(String dpiId) throws SQLException {

//        hibernateSessionFactory.getCache().evictEntityRegion(Messageincominglog.class);
//        hibernateSessionFactory.getCache().evictEntityRegion(Versionreported.class);
//        Session session = hibernateSessionFactory.openSession();
        init();
//        Object rvcheckstatusObject = session.get(Rvcheckstatus.class, Integer.parseInt(dpiId));
        String sql = "select * from Rvcheckstatus where dpiId='" + dpiId+"'";
        Object[] params = {};
        JSONObject obj = new JSONObject();
        rs = baseDao.executeSQL(sql, params);
        long lastCheckTime = 946656000000l; // 2000年1月1日 00:00:00
//        if (rvcheckstatusObject == null) {
        if (!rs.next()) {
            Rvcheckstatus status = new Rvcheckstatus(Integer.parseInt(dpiId), new Date(System.currentTimeMillis()));
//            Transaction tx = null;
            try {
                Object[] param = {status.getDpiId(), status.getLastCheckTime()};
                String sql1 = "insert into Rvcheckstatus (dpiId,lastCheckTime) values (?, ?)";
                baseDao.executeUpdate(sql1, param);
//                tx = session.beginTransaction();
//                session.save(status);
//                tx.commit();

            } catch (Exception e) {
                e.printStackTrace();
//                tx.rollback();
            }
        } else {
            Rvcheckstatus status = (Rvcheckstatus) rs.getObject("lastCheckTime");
//            Rvcheckstatus status = (Rvcheckstatus) rvcheckstatusObject;
            lastCheckTime = status.getLastCheckTime().getTime();
        }

        Date lastTimePtr = new Date(lastCheckTime);

        try {
            Versionreported bean = null;
            String sql1 = "select * from Dpiendpointbean where id='" + dpiId+"'";
            Object[] param = {};
            JSONObject objj = new JSONObject();
            rs = baseDao.executeSQL(sql1, param);
            Map<String, Integer> map = new HashMap<String, Integer>();
            Policyrepositoryinstance priPtr = null;

            for (Object piObj : new HashSet(0)) {
                priPtr = (Policyrepositoryinstance) piObj;
                map.put(priPtr.getPolicyrepositorytype().getMessageType(), priPtr.getId());

            }
            System.out.println("==>[Function GetReportedVersion]");
            System.out.println("=>DPI Configured map: " + rs.getString("name"));
            System.out.println("=>" + map.toString());
            Messageincominglog log = null;
            Object[] para = {dpiId};
            rs = baseDao.executeSQL("SELECT * FROM Messageincominglog where id=?", para);


            while (!rs.next()) {

                Transaction tx = null;

                xC2 c2 = new xC2();
                try {
                    c2.parseBinary(log.getPacket());
                } catch (Exception e) {
                    System.out.println("==>[Packet Exception][IN][C2][LOG:" + log.getId() + "][" + rs.getString("name") + "][" + rs.getString("masterIp") + "]");
                    continue;
                }
                System.out.println("=>logid=" + log.getId());
                System.out.println("=>parsedC2=" + c2.getPolicys().toString());
                String msgType = null;
                for (xC2.Message m : c2.getPolicys()) {
                    msgType = "0x" + HexUtil.getHex(m.getMessageType().toByte());
                    System.out.println("=>processing:logid:" + log.getId() + ",msgType:" + msgType);
                    if (map.containsKey(msgType)) {
                        try {
                            Versionreported vr = new Versionreported();
//                                vr.setDpiendpointbean(dpiBean);

//                                vr.setPolicyrepositoryinstance((Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, map.get(msgType)));
//                                vr.setPolicyrepositoryinstance((Policyrepositoryinstance) baseDao.executeSQL("SELECT * FROM Policyrepositoryinstance where id=?", para);
                            baseDao.executeSQL("SELECT * FROM Policyrepositoryinstance where id=?", para);
                            VersionreportedId vid = new VersionreportedId(Integer.parseInt(dpiId), map.get(msgType));
                            vr.setId(vid);
                            vr.setMessageSerialNo(m.getMessageSerialNo().toLong());
                            vr.setReportTime(log.getTime());
//                                session.saveOrUpdate(vr);
                            String sq = "insert into versionreported(reportTime ,messageSerialNo ,DPIEndPointBean_id ,PolicyRepositoryInstance_id) values(?,?,?,?)";
                            Object[] par = {log.getTime(), m.getMessageSerialNo().toLong(), rs.getString("id"), vid};
                            baseDao.executeUpdate(sq, par);
                            System.out.println("=>saveOrUpdated:<" + vr.getId().getDpiendPointBeanId() + "," + vr.getId().getPolicyRepositoryInstanceId() + ">");

                            String sqll = "update Rvcheckstatus lastCheckTime=" + lastCheckTime + " where dpiId=" + dpiId;
                            Object[] p = {};
                            baseDao.executeUpdate(sqll, p);
//                                session.evict(vr);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }


            JSONObject config = new JSONObject();
            Policyrepositoryinstance pri = null;
//            session.refresh(dpiBean);
            for (Object piObj : new HashSet(0)) {
                pri = (Policyrepositoryinstance) piObj;
                JSONObject in = new JSONObject();
                in.put("version", "-1");
                in.put("time", "-");
                in.put("configured", true);
                config.put(pri.getPolicyrepositorytype().getMessageType(), in);
            }
            System.out.println("=>configuredJSON=" + config.toString(4));

            rs = baseDao.executeSQL("SELECT * FROM Versionreported where PolicyRepositoryInstance_id=?", para);
            String messageType = null;
            while (rs.next()) {
                messageType = bean.getPolicyrepositoryinstance().getPolicyrepositorytype().getMessageType();
                if (config.has(messageType)) {
                    JSONObject in = config.getJSONObject(messageType);
                    in.put("version", bean.getMessageSerialNo());
                    in.put("time", sdf.format(bean.getReportTime()));
                } else {
                    JSONObject in = new JSONObject();
                    in.put("version", bean.getMessageSerialNo());
                    in.put("time", sdf.format(bean.getReportTime()));
                    in.put("configured", false);
                    config.put(messageType, in);
                }
            }

//            Versionreported bean = null;
//            Dpiendpointbean dpiBean = (Dpiendpointbean) session.get(Dpiendpointbean.class, Integer.parseInt(dpiId));


//            Map<String, Integer> map = new HashMap<String, Integer>();
//            Policyrepositoryinstance priPtr = null;
//            for (Object piObj : dpiBean.getPolicyrepositoryinstances()) {
//                priPtr = (Policyrepositoryinstance) piObj;
//                map.put(priPtr.getPolicyrepositorytype().getMessageType(), priPtr.getId());
//
//            }

//            System.out.println("==>[Function GetReportedVersion]");
//            System.out.println("=>DPI Configured map: " + dpiBean.getName());
//            System.out.println("=>" + map.toString());
//            Messageincominglog log = null;
//            Query q1 = session.createQuery("SELECT log FROM Messageincominglog AS log where log.dpiendpointbean.id=:dpiId and log.messageType=:messageType and log.time > :lastCheckTime ORDER BY log.time");
//            q1.setParameter("messageType", "0xC2");
//            q1.setParameter("dpiId", dpiBean.getId());
//            q1.setParameter("lastCheckTime", lastTimePtr);
//            List c2log = q1.list();
//            if (!c2log.isEmpty()) {
//                for (Object logObj : c2log) {
//                    log = (Messageincominglog) logObj;
//                    Transaction tx = null;
//
//                    xC2 c2 = new xC2();
//                    try {
//                        c2.parseBinary(log.getPacket());
//                    } catch (Exception e) {
//                        System.out.println("==>[Packet Exception][IN][C2][LOG:" + log.getId() + "][" + dpiBean.getName() + "][" + dpiBean.getMasterIp() + "]");
//                        continue;
//                    }
//                    System.out.println("=>logid=" + log.getId());
//                    System.out.println("=>parsedC2=" + c2.getPolicys().toString());
//                    String msgType = null;
//                    for (xC2.Message m : c2.getPolicys()) {
//                        msgType = "0x" + HexUtil.getHex(m.getMessageType().toByte());
//                        System.out.println("=>processing:logid:" + log.getId() + ",msgType:" + msgType);
//                        if (map.containsKey(msgType)) {
//                            try {
//                                tx = session.beginTransaction();
//                                Versionreported vr = new Versionreported();
//                                vr.setDpiendpointbean(dpiBean);
//
//                                vr.setPolicyrepositoryinstance((Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, map.get(msgType)));
//                                VersionreportedId vid = new VersionreportedId(Integer.parseInt(dpiId), map.get(msgType));
//                                vr.setId(vid);
//                                vr.setMessageSerialNo(m.getMessageSerialNo().toLong());
//                                vr.setReportTime(log.getTime());
//                                session.saveOrUpdate(vr);
//                                System.out.println("=>saveOrUpdated:<" + vr.getId().getDpiendPointBeanId() + "," + vr.getId().getPolicyRepositoryInstanceId() + ">");
//                                session.createQuery("update Rvcheckstatus r set r.lastCheckTime=:time where r.dpiId=:dpiId").setParameter("time", new Date(System.currentTimeMillis())).setParameter("dpiId", Integer.parseInt(dpiId)).executeUpdate();
//                                tx.commit();
//                                session.evict(vr);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                                tx.rollback();
//                            }
//                        }
//                    }
//
//                }
//            }

//            JSONObject config = new JSONObject();
//            Policyrepositoryinstance pri = null;
//            session.refresh(dpiBean);
//            for (Object piObj : dpiBean.getPolicyrepositoryinstances()) {
//                pri = (Policyrepositoryinstance) piObj;
//                JSONObject in = new JSONObject();
//                in.put("version", "-1");
//                in.put("time", "-");
//                in.put("configured", true);
//                config.put(pri.getPolicyrepositorytype().getMessageType(), in);
//            }
//            System.out.println("=>configuredJSON=" + config.toString(4));

//            Query q = session.createQuery("SELECT reported FROM Versionreported AS reported where reported.dpiendpointbean.id=:dpiId");
//            q.setParameter("dpiId", dpiBean.getId());
//            java.util.List l = q.list();

//            String messageType = null;
//            for (Object o : l) {
//
//                bean = (Versionreported) o;
//                messageType = bean.getPolicyrepositoryinstance().getPolicyrepositorytype().getMessageType();
//                if (config.has(messageType)) {
//                    JSONObject in = config.getJSONObject(messageType);
//                    in.put("version", bean.getMessageSerialNo());
//                    in.put("time", sdf.format(bean.getReportTime()));
//                } else {
//                    JSONObject in = new JSONObject();
//                    in.put("version", bean.getMessageSerialNo());
//                    in.put("time", sdf.format(bean.getReportTime()));
//                    in.put("configured", false);
//                    config.put(messageType, in);
//                }
//            }
            System.out.println("=>finalJSON=" + config.toString(4));
            try {
                return config.toString();
            } catch (Exception e) {
                return "{}";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "{}";
        } finally {
            close();
//            session.close();
        }
    }
}
